package com.gateon.hw.base.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import springfox.documentation.spring.web.json.Json;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Setter
@Getter
@Slf4j
@ApiModel("统一响应类")
public class Result<T> implements Serializable {

    public static Result SUCCESS = new Result();

    private String msg = "操作成功";

    private int code = 0;

    private T data;

    public Result() {
    }


    public boolean success() {
        return this.code == 0;
    }

    private Result(T data) {
        this.data = data;
    }


    private Result(int code, String msg) {
        this.msg = msg;
        this.code = code;
    }

    public static <T> Result<T> fail(int code, String msg) {
        return new Result<>(code, msg);
    }

    public static <T> Result<T> fail(String msg, T t) {
        Result<T> result = new Result<>(-1, msg);
        result.data = t;
        return result;
    }



    public static <T> Result<T> validMsg(BindingResult bindingResult) {
        Result r=new Result();
        r.setCode(-1);
        Map<String,String> msg=new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            msg.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        r.setMsg(JSON.toJSONString(msg));
        return r;
    }

    public static <T> Result<T> withData(T data) {
        Result<T> result = new Result<>();
        result.data = data;
        return result;
    }


    public static <T> Result<T> fail(String msg) {
        return new Result<>(-1, msg);
    }
}
